<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>JVM学习-垃圾回收 | Pei's Blog</title><meta name="keywords" content="JVM,Java"><meta name="author" content="Pei"><meta name="copyright" content="Pei"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="虽然没用过，但是得卷啊">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM学习-垃圾回收">
<meta property="og:url" content="https://blog.goku.top/posts/53914.html">
<meta property="og:site_name" content="Pei&#39;s Blog">
<meta property="og:description" content="虽然没用过，但是得卷啊">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://qiniu.goku.top/blog/jvm.jpeg">
<meta property="article:published_time" content="2021-12-04T04:18:40.000Z">
<meta property="article:modified_time" content="2023-10-17T00:12:33.721Z">
<meta property="article:author" content="Pei">
<meta property="article:tag" content="JVM">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://qiniu.goku.top/blog/jvm.jpeg"><link rel="shortcut icon" href="http://qiniu.goku.top/blog/icon.png"><link rel="canonical" href="https://blog.goku.top/posts/53914"><link rel="preconnect" href="//cdn.jsdelivr.net"/><meta name="google-site-verification" content="培的博客"/><meta name="baidu-site-verification" content="培的博客"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.2/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/snackbarjs/1.1.0/snackbar.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/fancyapps-ui/5.0.22/fancybox/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"该文章已发布","messageNext":"天，文章信息部分有效性请以实际为准。"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":400},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JVM学习-垃圾回收',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2023-10-17 08:12:33'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/html/css/plane_v2.css"><link rel="stylesheet" href="/html/css/universe.css"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="/html/css/fengche.css"><link rel="stylesheet" href="/html/css/twikoo_beautify.css"><link rel="stylesheet" type="text/css" href="/html/css/heoMainColor.css"><link rel="stylesheet" type="text/css" href="/html/css/poem.css"><link rel="stylesheet" type="text/css" href="/html/css/snackbar.css"><link rel="stylesheet" href="https://cdn1.tianli0.top/gh/zhheo/Post-Abstract-AI@0.15.2/tianli_gpt.css"><link rel="stylesheet" href="/html/css/goku.css"><link rel="stylesheet" href="/html/css/custom_foot.css"><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://thirdqq.qlogo.cn/g?b=sdk&amp;k=C88w6ZftQk9ibgdcM4sH4jg&amp;s=140&amp;t=1657271033" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/random.html"><i class="fa-fw fa-solid fa-shuffle"></i><span> 随机一文</span></a></div><div class="menus_item"><a class="site-page" href="/webstack.html"><i class="fa-fw fa-solid fa-star"></i><span> 网址导航</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/posts/d10ad42e.html"><span> 堵猫猫</span></a></li><li><a class="site-page child" href="/posts/fc4d392a.html"><span> 烟花秀</span></a></li><li><a class="site-page child" href="/html/TheMatrix/index.html"><span> 黑客帝国</span></a></li><li><a class="site-page child" href="/html/Glare/index.html"><span> 炫光</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/artitalk"><i class="fa-fw fas fa-comment-dots"></i><span> 说说</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa-solid fa-blog"></i><span> 博客</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Pei's Blog</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/random.html"><i class="fa-fw fa-solid fa-shuffle"></i><span> 随机一文</span></a></div><div class="menus_item"><a class="site-page" href="/webstack.html"><i class="fa-fw fa-solid fa-star"></i><span> 网址导航</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/posts/d10ad42e.html"><span> 堵猫猫</span></a></li><li><a class="site-page child" href="/posts/fc4d392a.html"><span> 烟花秀</span></a></li><li><a class="site-page child" href="/html/TheMatrix/index.html"><span> 黑客帝国</span></a></li><li><a class="site-page child" href="/html/Glare/index.html"><span> 炫光</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/artitalk"><i class="fa-fw fas fa-comment-dots"></i><span> 说说</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa-solid fa-blog"></i><span> 博客</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div></div></div><div id="nav-right"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i></a></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">JVM学习-垃圾回收</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2021-12-04T04:18:40.000Z" title="发表于 2021-12-04 12:18:40">2021-12-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span></div></div></div><article class="post-content" id="article-container"><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">网上学习的JVM课程，跟随视频自己做的笔记</span><br></pre></td></tr></table></figure>
<h4 id="一、如何判断对象是否可以被回收："><a href="#一、如何判断对象是否可以被回收：" class="headerlink" title="一、如何判断对象是否可以被回收："></a>一、如何判断对象是否可以被回收：</h4><h5 id="1-引用计数法：对象被其他对象引用计数-1，不再引用就-1，0就表示可以被回收掉了。"><a href="#1-引用计数法：对象被其他对象引用计数-1，不再引用就-1，0就表示可以被回收掉了。" class="headerlink" title="1. 引用计数法：对象被其他对象引用计数+1，不再引用就-1，0就表示可以被回收掉了。"></a>1. 引用计数法：对象被其他对象引用计数+1，不再引用就-1，0就表示可以被回收掉了。</h5><ul>
<li>弊端：如果两个对象互相引用，各自的计数都是1，但是没有其他对象引用他们，就不能被回收。<img src= "" data-lazy-src="https://img-blog.csdnimg.cn/2020112213260158.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTkwMjkw,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></li>
</ul>
<h5 id="2-可达性分析算法："><a href="#2-可达性分析算法：" class="headerlink" title="2. 可达性分析算法："></a>2. 可达性分析算法：</h5><ul>
<li>垃圾回收之前，会对堆内存进行扫描，来检测每个对象是否会被根对象（GC Root）直接或间接引用，如果是那么这个对象不能被回收，反之则可以回收。</li>
<li>举个例子：像一串葡萄一样，如果把葡萄从顶部提起来，跟随葡萄一同起来的葡萄果代表不能被回收的对象，而那些断开散落的则是能被回收的对象。</li>
<li>哪些对象可以被作为GC Root？<br>可以通过eclipse提供的工具Memory Analyzer来分析。<br>System Class（系统核心类）、Native Stack、Busy Monitor（正在加锁的对象）、Thread（活动线程类）、栈帧内使用的对象。<br>比如一个方法内声明了List<String> list &#x3D; new ArrayList&lt;&gt;();则该ArrayList即可作为GC Root。</li>
</ul>
<h5 id="3-四种引用（细分有五种）"><a href="#3-四种引用（细分有五种）" class="headerlink" title="3.  四种引用（细分有五种）"></a>3.  四种引用（细分有五种）</h5><h6 id="3-1-强引用"><a href="#3-1-强引用" class="headerlink" title="3.1 强引用"></a>3.1 强引用</h6><p>Obj obj &#x3D; new Obj();<br>只要所有GC Roots对象都不通过强引用引用该对象，该对象才能被回收。</p>
<h6 id="3-2-软引用（SoftReference）"><a href="#3-2-软引用（SoftReference）" class="headerlink" title="3.2 软引用（SoftReference）"></a>3.2 软引用（SoftReference）</h6><ul>
<li>仅有软引用引用该对象时，在垃圾回收后，内存仍不够才会回收软引用对象。</li>
<li>可以配合引用队列来释放软引用自身</li>
<li>适用场景：数据缓存</li>
</ul>
<h6 id="3-3-弱引用（WeakReference）"><a href="#3-3-弱引用（WeakReference）" class="headerlink" title="3.3 弱引用（WeakReference）"></a>3.3 弱引用（WeakReference）</h6><ul>
<li>仅有弱引用引用该对象时，在垃圾回收时，无论内存是否充足，都会回收弱引用对象。</li>
<li>可以配合引用队列类释放弱引用自身</li>
</ul>
<h6 id="3-4-虚引用（PhantomReference幽灵引用）"><a href="#3-4-虚引用（PhantomReference幽灵引用）" class="headerlink" title="3.4 虚引用（PhantomReference幽灵引用）"></a>3.4 虚引用（PhantomReference幽灵引用）</h6><ul>
<li>必须配合引用队列使用，主要配合ByteBuffer使用，被引用对象回收时，会将虚引用入队列，由Reference Handler线程调用虚引用相关方法释放直接内存。</li>
</ul>
<h6 id="3-5-终结器引用（FinalReference）"><a href="#3-5-终结器引用（FinalReference）" class="headerlink" title="3.5 终结器引用（FinalReference）"></a>3.5 终结器引用（FinalReference）</h6><ul>
<li>无需手动编码，但其内部配合引用队列使用，在垃圾回收时，终结器引用入队（被引用对象暂时没有被回收），再由Finalizer线程（优先级低）通过终结器引用找到被引用对象并调用他的finalize方法，第二次GC时才能回收被引用对象。</li>
</ul>
<h4 id="二、-垃圾回收算法"><a href="#二、-垃圾回收算法" class="headerlink" title="二、 垃圾回收算法"></a>二、 垃圾回收算法</h4><p>JVM会根据情况采用下面三种算法。</p>
<h5 id="1-标记清除（Mark-Sweep）"><a href="#1-标记清除（Mark-Sweep）" class="headerlink" title="1. 标记清除（Mark Sweep）"></a>1. 标记清除（Mark Sweep）</h5><p>先标记再清除，效率相对来说快，但是会产生内存碎片，造成内存不连续。<br>优点：效率高<br>缺点：会产生内存碎片</p>
<h5 id="2-标记整理（Mark-Compact）"><a href="#2-标记整理（Mark-Compact）" class="headerlink" title="2. 标记整理（Mark Compact）"></a>2. 标记整理（Mark Compact）</h5><p>标记清除完会对内存进行整理， 将可用对象向前移动使内存更加连续，还要更新对象的引用地址，所以效率相对来说较低。<br>优点：不会产生碎片<br>缺点：效率相对较低</p>
<h5 id="3-复制（Copy）"><a href="#3-复制（Copy）" class="headerlink" title="3. 复制（Copy）"></a>3. 复制（Copy）</h5><p>将内存区域划分为两块区域，from区域和to区域，先找到存活的对象进行标记，将存活的对象复制到to并且进行内存整理，然后将from和to进行交换。<br>优点：不会产生碎片<br>缺点：占用双倍的内存空间</p>
<h4 id="三、-分代垃圾回收机制"><a href="#三、-分代垃圾回收机制" class="headerlink" title="三、 分代垃圾回收机制"></a>三、 分代垃圾回收机制</h4><p><img src= "" data-lazy-src="https://img-blog.csdnimg.cn/20201122142214318.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTkwMjkw,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
<ol>
<li>创建新的对象时，默认采用伊甸园的内存</li>
<li>当伊甸园内存不足时，会发生Minor GC，对伊甸园进行一次垃圾回收，并采用复制算法将对象存放在幸存区to，年龄+1（to和from会交换位置）</li>
<li>经过第一次垃圾回收之后，伊甸园的内存又充足了，当伊甸园内存再次不足时会发生第二次Minor GC，此时会对伊甸园和幸存区from进行垃圾回收，也会将存活的对象存放到to，年龄+1并交换to和from位置。</li>
<li>存活的对象不会一直在幸存区，当年龄超过一定的阈值（最大为15，因为是4bit，最大为1111）会认为该对象价值高经常被使用，会晋升至老年代。</li>
<li>当新生代和老年代内存都不足时会先尝试Minor GC，如果仍不足，会触发Full GC，来进行整个内存清理。</li>
<li>补充：GC时，会发生STW（stop the world）（因为采用复制算法，对象的地址会发生改变），暂停其他用户线程，等待垃圾回收结束，用户线程才恢复运行。Full GC的STW时间更长。</li>
</ol>
<h4 id="四、相关VM参数"><a href="#四、相关VM参数" class="headerlink" title="四、相关VM参数"></a>四、相关VM参数</h4><p><img src= "" data-lazy-src="https://img-blog.csdnimg.cn/20201122144438556.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTkwMjkw,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
<h4 id="五、垃圾回收器"><a href="#五、垃圾回收器" class="headerlink" title="五、垃圾回收器"></a>五、垃圾回收器</h4><h5 id="1、串行垃圾回收器"><a href="#1、串行垃圾回收器" class="headerlink" title="1、串行垃圾回收器"></a>1、串行垃圾回收器</h5><p><img src= "" data-lazy-src="https://img-blog.csdnimg.cn/20201124100715333.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTkwMjkw,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>开启指令：-XX:+UseSerialGC&#x3D;Serial+SerialOld<br>Serial为新生代垃圾回收器，采用复制算法。<br>SerialOld为老年代，采用标记+整理算法。<br>都为单线程的，垃圾回收时都会STW。</p>
<h5 id="2、吞吐量优先垃圾回收器"><a href="#2、吞吐量优先垃圾回收器" class="headerlink" title="2、吞吐量优先垃圾回收器"></a>2、吞吐量优先垃圾回收器</h5><p><img src= "" data-lazy-src="https://img-blog.csdnimg.cn/2020112410134299.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTkwMjkw,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>参数一：并行的垃圾回收器，JDK1.8默认的垃圾回收器。<br>参数二：采用自适应调整伊甸园，晋升阈值和幸存区大小。<br>两个目标：<br>参数三：计算公式：1&#x2F;(1+ratio)，比如radio是99，则公式得0.01，即100分钟内最多有1分钟来进行垃圾回收，如果达不到这个目标则会调整堆内存，一般是调大，来减少垃圾回收的次数，来提高系统吞吐量。一般设置19。<br>参数四：最大停留ms数，默认200ms。与上边是冲突的，因为如果上边有做出调大堆内存，那么停留时间可能就会变长，导致达不到这一目标。<br>这两个是冲突的。<br>参数五：控制垃圾回收时并行的线程数量。</p>
<h5 id="3、响应时间优先的垃圾回收器（CMS）"><a href="#3、响应时间优先的垃圾回收器（CMS）" class="headerlink" title="3、响应时间优先的垃圾回收器（CMS）"></a>3、响应时间优先的垃圾回收器（CMS）</h5><p><img src= "" data-lazy-src="https://img-blog.csdnimg.cn/20201124103319341.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTkwMjkw,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>-XX:+UseConcMarkSweepGC ~ -XX:+UseParNewGC ~ SerialOld<br>是工作在老年代基于标记清除算法的垃圾回收器，并发失败会降级为SerialOld串行垃圾回收器。<br>初始标记和重新标记会STW，初始标记只标记根对象，因为并发标记时用户线程也在执行，会产生新的垃圾，所以需要重新标记。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Pei</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://blog.goku.top/posts/53914.html">https://blog.goku.top/posts/53914.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://blog.goku.top" target="_blank">Pei's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JVM/">JVM</a><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="http://qiniu.goku.top/blog/jvm.jpeg" data-sites="wechat,weibo,qq,facebook,twitter"></div><link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.bootcdn.net/ajax/libs/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wxpay.jpeg" target="_blank"><img class="post-qr-code-img" src="/img/wxpay.jpeg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.jpeg" target="_blank"><img class="post-qr-code-img" src="/img/alipay.jpeg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/39748.html"><img class="prev-cover" src="http://qiniu.goku.top/blog/post_banner_3.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">MySQL存储过程学习</div></div></a></div><div class="next-post pull-right"><a href="/posts/25871.html"><img class="next-cover" src="http://qiniu.goku.top/blog/post_banner_9.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">（已解决）SpringBoot微信公众号服务器配置时验证通过却提示配置失败</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/9365.html" title="JVM学习-类加载"><img class="cover" src="http://qiniu.goku.top/blog/jvm.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-23</div><div class="title">JVM学习-类加载</div></div></a></div><div><a href="/posts/8275.html" title="Spring中使用模板方法模式(接上文)"><img class="cover" src="http://qiniu.goku.top/blog/post_banner_6.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-13</div><div class="title">Spring中使用模板方法模式(接上文)</div></div></a></div><div><a href="/posts/8baa02f7.html" title="mac自用开发环境记录"><img class="cover" src="http://qiniu.goku.top/blog/mac.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-31</div><div class="title">mac自用开发环境记录</div></div></a></div><div><a href="/posts/22676.html" title="Spring项目中使用策略模式和工厂模式"><img class="cover" src="http://qiniu.goku.top/blog/post_banner_10.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-04</div><div class="title">Spring项目中使用策略模式和工厂模式</div></div></a></div><div><a href="/posts/51466.html" title="面试专题-并发篇"><img class="cover" src="http://qiniu.goku.top/blog/ms_concurrent.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-18</div><div class="title">面试专题-并发篇</div></div></a></div><div><a href="/posts/25871.html" title="（已解决）SpringBoot微信公众号服务器配置时验证通过却提示配置失败"><img class="cover" src="http://qiniu.goku.top/blog/post_banner_9.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-06-26</div><div class="title">（已解决）SpringBoot微信公众号服务器配置时验证通过却提示配置失败</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://thirdqq.qlogo.cn/g?b=sdk&amp;k=C88w6ZftQk9ibgdcM4sH4jg&amp;s=140&amp;t=1657271033" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Pei</div><div class="author-info__description">躺平虽然不好，但真的很爽</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/sgr997"><i class="fab fa-github"></i><span>联系我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/sgr997" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://www.coolapk.com/u/725902" target="_blank" title="酷安"><i class="fa-solid fa-c"></i></a><a class="social-icon" href="https://space.bilibili.com/49499302" target="_blank" title="bilibili"><i class="fa-brands fa-bilibili"></i></a></div></div><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople1.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/zdog.dist.js"></script><script id="rendered-js" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople.js"></script><style>.card-widget.card-announcement {
margin: 0;
align-items: center;
justify-content: center;
text-align: center;
}
canvas {
display: block;
margin: 0 auto;
cursor: move;
}</style><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%A6%82%E4%BD%95%E5%88%A4%E6%96%AD%E5%AF%B9%E8%B1%A1%E6%98%AF%E5%90%A6%E5%8F%AF%E4%BB%A5%E8%A2%AB%E5%9B%9E%E6%94%B6%EF%BC%9A"><span class="toc-number">1.</span> <span class="toc-text">一、如何判断对象是否可以被回收：</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E6%B3%95%EF%BC%9A%E5%AF%B9%E8%B1%A1%E8%A2%AB%E5%85%B6%E4%BB%96%E5%AF%B9%E8%B1%A1%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0-1%EF%BC%8C%E4%B8%8D%E5%86%8D%E5%BC%95%E7%94%A8%E5%B0%B1-1%EF%BC%8C0%E5%B0%B1%E8%A1%A8%E7%A4%BA%E5%8F%AF%E4%BB%A5%E8%A2%AB%E5%9B%9E%E6%94%B6%E6%8E%89%E4%BA%86%E3%80%82"><span class="toc-number">1.1.</span> <span class="toc-text">1. 引用计数法：对象被其他对象引用计数+1，不再引用就-1，0就表示可以被回收掉了。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90%E7%AE%97%E6%B3%95%EF%BC%9A"><span class="toc-number">1.2.</span> <span class="toc-text">2. 可达性分析算法：</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E5%9B%9B%E7%A7%8D%E5%BC%95%E7%94%A8%EF%BC%88%E7%BB%86%E5%88%86%E6%9C%89%E4%BA%94%E7%A7%8D%EF%BC%89"><span class="toc-number">1.3.</span> <span class="toc-text">3.  四种引用（细分有五种）</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#3-1-%E5%BC%BA%E5%BC%95%E7%94%A8"><span class="toc-number">1.3.1.</span> <span class="toc-text">3.1 强引用</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-2-%E8%BD%AF%E5%BC%95%E7%94%A8%EF%BC%88SoftReference%EF%BC%89"><span class="toc-number">1.3.2.</span> <span class="toc-text">3.2 软引用（SoftReference）</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-3-%E5%BC%B1%E5%BC%95%E7%94%A8%EF%BC%88WeakReference%EF%BC%89"><span class="toc-number">1.3.3.</span> <span class="toc-text">3.3 弱引用（WeakReference）</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-4-%E8%99%9A%E5%BC%95%E7%94%A8%EF%BC%88PhantomReference%E5%B9%BD%E7%81%B5%E5%BC%95%E7%94%A8%EF%BC%89"><span class="toc-number">1.3.4.</span> <span class="toc-text">3.4 虚引用（PhantomReference幽灵引用）</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-5-%E7%BB%88%E7%BB%93%E5%99%A8%E5%BC%95%E7%94%A8%EF%BC%88FinalReference%EF%BC%89"><span class="toc-number">1.3.5.</span> <span class="toc-text">3.5 终结器引用（FinalReference）</span></a></li></ol></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%8C%E3%80%81-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">二、 垃圾回收算法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E6%A0%87%E8%AE%B0%E6%B8%85%E9%99%A4%EF%BC%88Mark-Sweep%EF%BC%89"><span class="toc-number">2.1.</span> <span class="toc-text">1. 标记清除（Mark Sweep）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E6%A0%87%E8%AE%B0%E6%95%B4%E7%90%86%EF%BC%88Mark-Compact%EF%BC%89"><span class="toc-number">2.2.</span> <span class="toc-text">2. 标记整理（Mark Compact）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E5%A4%8D%E5%88%B6%EF%BC%88Copy%EF%BC%89"><span class="toc-number">2.3.</span> <span class="toc-text">3. 复制（Copy）</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E3%80%81-%E5%88%86%E4%BB%A3%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6"><span class="toc-number">3.</span> <span class="toc-text">三、 分代垃圾回收机制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E7%9B%B8%E5%85%B3VM%E5%8F%82%E6%95%B0"><span class="toc-number">4.</span> <span class="toc-text">四、相关VM参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E5%99%A8"><span class="toc-number">5.</span> <span class="toc-text">五、垃圾回收器</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1%E3%80%81%E4%B8%B2%E8%A1%8C%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E5%99%A8"><span class="toc-number">5.1.</span> <span class="toc-text">1、串行垃圾回收器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2%E3%80%81%E5%90%9E%E5%90%90%E9%87%8F%E4%BC%98%E5%85%88%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E5%99%A8"><span class="toc-number">5.2.</span> <span class="toc-text">2、吞吐量优先垃圾回收器</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3%E3%80%81%E5%93%8D%E5%BA%94%E6%97%B6%E9%97%B4%E4%BC%98%E5%85%88%E7%9A%84%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E5%99%A8%EF%BC%88CMS%EF%BC%89"><span class="toc-number">5.3.</span> <span class="toc-text">3、响应时间优先的垃圾回收器（CMS）</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/31488961.html" title="解决macos安装软件后提示已损坏问题">解决macos安装软件后提示已损坏问题</a><time datetime="2023-10-10T05:22:13.909Z" title="发表于 2023-10-10 13:22:13">2023-10-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/77213149.html" title="李跳跳自定义规则">李跳跳自定义规则</a><time datetime="2023-09-16T05:02:41.000Z" title="发表于 2023-09-16 13:02:41">2023-09-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/AI%E8%81%8A%E5%A4%A9%E7%BD%91%E7%AB%99.html" title="AI聊天网站推荐">AI聊天网站推荐</a><time datetime="2023-06-19T11:39:41.000Z" title="发表于 2023-06-19 19:39:41">2023-06-19</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/dd74890d.html" title="随记账本项目">随记账本项目</a><time datetime="2023-04-27T02:40:25.000Z" title="发表于 2023-04-27 10:40:25">2023-04-27</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/fc4d392a.html" title="一场烟花送给你">一场烟花送给你</a><time datetime="2023-02-18T13:34:14.000Z" title="发表于 2023-02-18 21:34:14">2023-02-18</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">关于博客</p><div class="bg-ad"><div>衷心感谢每一位光临我的博客的朋友</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://gg.goku.top">聊天问答</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">推荐网址</p><ul class="ft-links"><li><a target="_blank" rel="noopener" href="https://github.com/sgr997">Github</a><a href="/webstack.html">网址导航</a></li><li><a target="_blank" rel="noopener" href="http://qiniu.goku.top/wxpay.jpeg">来杯咖啡</a><a href="/artitalk/">留点什么</a></li><li><a href="/about/">关于博主</a><a href="/archives/">文章归档</a></li><li><a href="/categories/">文章分类</a><a href="/tags/">文章标签</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链</p><div class="ft-img-group"><div class="img-group-item"><a href="/webstack.html"><img src="http://qiniu.goku.top/blog/icon.png" alt="网址导航"/></a></div></div></div></div><div class="copyright">&copy;2020 - 2023  <i id="heartbeat" class="fa fas fa-heartbeat"></i> Pei</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://beian.miit.gov.cn/" target="_blank">豫ICP备2023023872号</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/fancyapps-ui/5.0.22/fancybox/fancybox.umd.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/vanilla-lazyload/17.8.4/lazyload.iife.min.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/snackbarjs/1.1.0/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>(() => {
  const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaidWrap.length) {
    window.runMermaid = () => {
      window.loadMermaid = true
      const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? '' : ''

      Array.from($mermaidWrap).forEach((item, index) => {
        const mermaidSrc = item.firstElementChild
        const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
        const mermaidID = 'mermaid-' + index
        const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
        mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
          mermaidSrc.insertAdjacentHTML('afterend', svgCode)
        })
      })
    }

    const loadMermaid = () => {
      window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
    }

    window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
  }
})()</script><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo.goku.top/',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.vemoji)'))
      }
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo.goku.top/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      document.getElementById('twikoo-count').innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.bootcdn.net/ajax/libs/twikoo/1.6.20/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo.goku.top/',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.bootcdn.net/ajax/libs/twikoo/1.6.20/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (false) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><canvas id="universe"></canvas><script defer src="/html/js/universe.js"></script><script defer src="/html/js/disablef12.js"></script><script src="/html/js/lunar.js"></script><script src="/html/js/day.js"></script><script type="text/javascript" src="https://cdn1.tianli0.top/npm/sweetalert2@8.19.0/dist/sweetalert2.all.js"></script><script async src="/html/js/justlovesmile.js"></script><script>let tianliGPT_postSelector = '\#post \#article-container';let tianliGPT_postURL = '\*/posts/\*';let tianliGPT_key = '123';</script><script data-pjax src="/html/js/summ.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/pjax/0.2.8/pjax.min.js"></script><script>let pjaxSelectors = ["title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script></div></body></html>